//
//  ZLPFindViewController.m
//  TangYi
//
//  Created by dllo on 15/10/27.
//  Copyright (c) 2015年 赵连鹏. All rights reserved.
//

#import "ZLPFindViewController.h"
#import "ZLPFindCollectionViewCell.h"
#import "ZLPListModel.h"
#import "ZLPTagModel.h"
#import "ZLPPicsModel.h"
#import "ZLPAuthorMdel.h"
#import <UIImageView+WebCache.h>
#import "ZLPSubDetailViewController.h"
#import <MJRefresh.h>
#import <AFNetworking.h>
#import <MBProgressHUD.h>

@interface ZLPFindViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property(nonatomic, retain) UICollectionView *collectionView;
@property(nonatomic, retain) NSMutableArray *listArr;
@property(nonatomic, retain) NSMutableArray *tagsArr;
@property(nonatomic, retain) NSMutableArray *picsArr;
@property(nonatomic, retain) NSMutableArray *authorArr;
@property(nonatomic, retain) UICollectionViewFlowLayout *layout;
@property(nonatomic, assign) NSInteger page;
@property(nonatomic, retain) MBProgressHUD *HUD;
@property(nonatomic, retain) UIImageView *image;

@end

@implementation ZLPFindViewController

- (void)dealloc {
    [_image release];
    [_HUD release];
    [_layout release];
    [_listArr release];
    [_collectionView release];
    [_tagsArr release];
    [_picsArr release];
    [_authorArr release];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"发现";
    
    [self createCollectionView];
    
    [self isWlan];
//    self.page = 0;
//    [self createData:self.page];
    
    [self headerRefresh];
    
    [self footerRefresh];
    
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.labelText = @"正在加载..";
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = NO;
}

- (void)isWlan {
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == 2 || status == 1) {
            self.page = 0;
            [self createData:self.page];
            self.image.hidden = YES;
            
        } else {
            [self.HUD removeFromSuperview];
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
            self.image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
            self.image.image = [UIImage imageNamed:@"outnetwork.png"];
            [self.view addSubview:self.image];
            [_image release];

        }
        
    }];
}


#pragma mark refresh
- (void)headerRefresh {
    
    [self.listArr removeAllObjects];
    
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       
        self.page = 0;
        [self createData:self.page];
        
    }];
}

- (void)footerRefresh {
    
    self.collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        self.page++;
        [self createData:self.page];
        
    }];
    
}

#pragma mark createCollectionView
- (void)createCollectionView {
    self.layout = [[UICollectionViewFlowLayout alloc] init];
    self.layout.itemSize = CGSizeMake(WIDTH / 2 - 20, HEIGHT / 2);
    
    self.layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) collectionViewLayout:self.layout];
    [self.view addSubview:self.collectionView];
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [_collectionView release];
    
    
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    [self.collectionView registerClass:[ZLPFindCollectionViewCell class] forCellWithReuseIdentifier:@"collection"];
}

#pragma mark createData
- (void)createData:(NSInteger)nextPage {
    
    NSString *strURL = @"http://open3.bantangapp.com/community/post/editorRec";
    NSURL *url = [NSURL URLWithString:strURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *bodyStr = [NSString stringWithFormat:@"app_installtime=1445349591.654459&app_versions=4.2.2&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&last_time=1446185019&oauth_token=8e93baa2127b39cbf64d15bfee8cff56&os_versions=9.1&page=%ld&pagesize=10&screensize=640&track_device_info=iPhone6%%2C2&track_deviceid=A5849E0F-EF33-4B83-80B1-0B846EE0DB3B&track_user_id=1457728&v=7", self.page];
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyData];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        if (data != nil) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            
            
            
            if (self.page == 0) {
                
                self.listArr = [NSMutableArray array];
                self.picsArr = [NSMutableArray array];
                self.tagsArr = [NSMutableArray array];
                self.authorArr = [NSMutableArray array];
                
                self.listArr = [ZLPListModel baseModelByArr:dic[@"data"][@"list"]];
                
                for (NSDictionary *temp in dic[@"data"][@"list"]) {
                    
                    ZLPPicsModel *picModel = [[ZLPPicsModel alloc] init];
                    for (NSDictionary *pic in temp[@"pics"]) {
                        [picModel setValuesForKeysWithDictionary:pic];
                    }
                    [self.picsArr addObject:picModel];
                    [picModel release];
                    
                    
                    ZLPTagModel *tagModel = [[ZLPTagModel alloc] init];
                    for (NSDictionary *tag in temp[@"tags"]) {
                        [tagModel setValuesForKeysWithDictionary:tag];
                    }
                    [self.tagsArr addObject:tagModel];
                    [tagModel release];
                    
                    ZLPAuthorMdel *authorModel = [[ZLPAuthorMdel alloc] init];
                    [authorModel setValuesForKeysWithDictionary:temp[@"author"]];
                    [self.authorArr addObject:authorModel];
                    [authorModel release];
                    
                }
            } else {
                NSMutableArray *tempArr = [NSMutableArray array];
                tempArr = [ZLPListModel baseModelByArr:dic[@"data"][@"list"]];
                for (ZLPListModel *temp in tempArr) {
                    [self.listArr addObject:temp];
                }
                
                for (NSDictionary *temp in dic[@"data"][@"list"]) {
                    
                    
                    NSMutableArray *tempPicArr = [NSMutableArray array];
                    tempPicArr = [ZLPPicsModel baseModelByArr:temp[@"pics"]];
                    for (ZLPPicsModel *tempPic in tempPicArr) {
                        [self.picsArr addObject:tempPic];
                    }
                    
                    NSMutableArray *tempTapArr = [NSMutableArray array];
                    tempTapArr = [ZLPTagModel baseModelByArr:temp[@"tags"]];
                    for (ZLPTagModel *tempTag in tempTapArr) {
                        [self.tagsArr addObject:tempTag];
                    }
                    
                    
                    NSMutableArray *tempAuthorArr = [NSMutableArray array];
                    ZLPAuthorMdel *tempAuthor = [[ZLPAuthorMdel alloc] init];
                    [tempAuthor setValuesForKeysWithDictionary:temp[@"author"]];
                    [tempAuthorArr addObject:tempAuthor];
                    [tempAuthor release];
                    for (ZLPAuthorMdel *tempAuthor in tempAuthorArr) {
                        [self.authorArr addObject:tempAuthor];
                    }
                    
                }
                
                
            }
            

//            NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//            // 拼接文件夹名
//            NSString *DicFile = [sandBoxPath stringByAppendingPathComponent:@"Find"];
//            // 创建文件管理者
//            NSFileManager *manager = [NSFileManager defaultManager];
//            // 通过管理者调用方法 根据路径判断文件夹是否存在
//            if (![manager fileExistsAtPath:DicFile]) {
//                // 创建文件夹
//                [manager createDirectoryAtPath:DicFile withIntermediateDirectories:YES attributes:nil error:nil];
//            }
//            NSLog(@"%@", DicFile);
//
//            
//            NSString *findSandBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//            NSString *docPath = [findSandBoxPath stringByAppendingPathComponent:@"Find/dic.plist"];
//            NSMutableArray *dicArr = [NSKeyedUnarchiver unarchiveObjectWithFile:docPath];
//            if (dicArr == nil) {
//                dicArr = [NSMutableArray array];
//            }
//            [dicArr addObject:dic];
//            // 归档
//            [NSKeyedArchiver archiveRootObject:dicArr toFile:docPath];
//            NSLog(@"findcache--%@", docPath);

            
            [self.collectionView.header endRefreshing];
            [self.collectionView.footer endRefreshing];
            [self.HUD removeFromSuperview];
            [self.collectionView reloadData];
        } else {
            [self.HUD removeFromSuperview];
            //            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            //            [alert show];
           
        }
        
    }];

    
}

#pragma mark collentionView的协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.listArr.count;
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZLPFindCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collection" forIndexPath:indexPath];
    
    
    ZLPPicsModel *picModel = [[ZLPPicsModel alloc] init];
    picModel = self.picsArr[indexPath.row];
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:picModel.url] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    cell.descLabel.text = [self.listArr[indexPath.row] content];
    cell.descLabel.numberOfLines = 0;
    cell.tagLabel.text = [self.tagsArr[indexPath.row] name];
    cell.nameLabel.text = [NSString stringWithFormat:@"by %@", [self.authorArr[indexPath.row] username]];
    [cell.avatarImageView sd_setImageWithURL:[NSURL URLWithString:[self.authorArr[indexPath.row] avatar]] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    
    
//    [cell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ZLPSubDetailViewController *detailVC = [[ZLPSubDetailViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
    
    detailVC.numID = [self.listArr[indexPath.row] numID];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
